<template>
  <uni-popup ref="popupRef" background-color="#fff" type="bottom">
    <view class="top-btn-cont">
      <text class="top-btn" @click="handleCancel">取消</text>
      <text class="top-btn" @click="handleSubmit">确定</text>
    </view>
    <view class="main-cont">
      <uni-data-checkbox v-bind="$attrs" v-model="checkValue" :multiple="true" mode="button"
                         :localdata="localData"></uni-data-checkbox>
    </view>
  </uni-popup>
</template>
<script setup>
import {nextTick, ref} from "vue";

const props = defineProps({
  defaultValue: String,
  localData: Array,
  returnWithText: Boolean, // 是否返回数据携带text
})
const emit = defineEmits(['selected', 'cancel'])
const checkValue = ref([])
const localData = ref([])

const popupRef = ref(null)
const handleSubmit = () => {
  if (props.returnWithText) {
    const selectedText = localData.value.filter(item => checkValue.value.includes(item.value))
    emit('selected', selectedText);
  } else {
    emit('selected', checkValue.value);
  }
  popupRef.value.close()
}
const handleCancel = () => {
  emit('cancel');
  popupRef.value.close()
}

const showPopup = async () => {
  await nextTick()
  checkValue.value = props.defaultValue.map(item => {
    return item.value ?? item
  })
  localData.value = props.localData
  popupRef.value.open(true)
}

defineExpose({
  showPopup
})
</script>

<style scoped lang="scss">
.top-btn-cont {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 40px;
  background-color: #f5f5f5;
  border-top: 1px solid #ccc;
  padding: 0 10px;
}

.main-cont {
  max-height: 50vh;
  overflow: auto;
  padding: 30rpx 20rpx;
}
</style>